package com.hqyj.ctxp.interceptor;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hqyj.ctxp.service.UserInfoService;
import com.hqyj.ctxp.service.UserService;
import com.hqyj.ctxp.utils.JwtUtils;
import com.hqyj.ctxp.utils.ResultInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * @className: JwtInterceptor
 * @description: TODO 类描述
 * @author: mmm
 * @date: 2022/12/6
 **/
@Component
public class JwtInterceptor implements HandlerInterceptor {

    public final static List<String> WHITE_URLS = new ArrayList<>();
    static {
        WHITE_URLS.add("/user/userLogin");
        WHITE_URLS.add("/user/userRegister");
        WHITE_URLS.add("/file/upload");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 如果请求不是映射到方法，直接跳过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 判断是否需要 Token 验证
        String path = request.getServletPath();
        if (!WHITE_URLS.stream().filter(item -> path.equals(item)).findFirst().isPresent()) {
            String token = request.getHeader("Token");
            if (StringUtils.isBlank(token)) {
                throw new Exception("No JWT Token.");
            }

            //获取Jwt对象
            String audience = JwtUtils.getAudience(token);
            DecodedJWT decodedJWT = JwtUtils.verifyToken(token, audience);
            if (decodedJWT == null) {
                throw new Exception("JWT verify failed.");
            }
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
